package com.common.aop;

import com.common.utils.JwtTokenUtils;
import com.common.vo.BaseVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author johnny
 * @create 2021-05-20 9:44 下午
 **/
@Aspect
@Component
@Slf4j
public class BindUpdateByAop {


    @Pointcut(value = "@annotation(com.common.base.BindUpdateBy)")
    public void bind() {
    }


    @Before("bind()")
    public void before(JoinPoint joinPoint) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            String operatorUser = JwtTokenUtils.getUserNameFromReq(request);
            Object[] args = joinPoint.getArgs();
            Arrays.stream(args).forEach(arg -> {
                if (arg instanceof BaseVo) {
                    ((BaseVo) arg).setUpdateBy(operatorUser);
                }
            });
        }

    }

}